package com.xy.manage.action;



import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.mysql.jdbc.log.Log;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.xy.common.page.Pagination;
import com.xy.common.util.DictUtils;
import com.xy.common.web.CookieUtils;
import com.xy.core.util.Constants;
import com.xy.core.web.WebErrors;
import com.xy.manage.model.Tinfo;
import com.xy.manage.model.Tuser;
import com.xy.manage.service.TinfoService;



@Controller
public class TinfoAction{
	private static final Logger log = LoggerFactory.getLogger(TinfoAction.class);
	public TinfoAction() {
	}
 
 
 	/**
	 * 信息管理新增页面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tinfoAdd.do")
	public String add(HttpServletRequest request, ModelMap model) {
		Tinfo t=new Tinfo();
		t.setCreatetime(new Date());
		model.addAttribute("tinfo", t);
		model.addAttribute("type", Integer.valueOf(request.getParameter("type")));
        setDict(model);
		return "tinfoEdit";
	}

	/**
	 * 信息管理新增保存
	 * 
	 * @param tinfo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/o_tinfoSave.do")
	public String save(Tinfo tinfo, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(tinfo, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		MultipartHttpServletRequest mh = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> m = mh.getFileMap();
		if (null != m.get("picfile")) {
			Set<String> set = m.keySet();
			for (String name : set) {
				MultipartFile mf = m.get(name);
				try {
					tinfo.setPic(mf.getBytes());
				} catch (IOException e) {
					tinfo.setPic(null);
					System.out.println("获取文件二进制数组错误");
					e.printStackTrace();
				}
			}
		}
		if (tinfo.getInfoid() == null) {
			Tuser user = (Tuser) request.getSession().getAttribute(Constants.ADMIN_AUTH_KEY);
			tinfo.setCreatetime(new Date());
			tinfo.setAuthor("梅州市公安局");
			tinfo.setOwner(user.getUsername());
		}

		tinfo = tinfoService.save(tinfo);
		if(Integer.valueOf(request.getParameter("type"))>999)
			return "redirect:v_tinfoListWorkGuide.do";
		else
			return "redirect:v_tinfoList.do?type=" + request.getParameter("type");
	}

	/**
	 * 信息管理删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("o_tinfoDelete.do")
	public String delete(long[] ids, HttpServletRequest request, ModelMap model) {
		if (ids != null) {
			for (long id : ids) {
				tinfoService.remove(id);
			}
		}
		if(Integer.valueOf(request.getParameter("type"))>999)
			return "redirect:v_tinfoListWorkGuide.do";
		else
			return "redirect:v_tinfoList.do?type="+request.getParameter("type");
	}

	/**
	 * 信息管理编辑页面
	 * 
	 * @param infoid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tinfoEdit.do")
	public String edit(long infoid, HttpServletRequest request, ModelMap model) {
		Tinfo tinfo = tinfoService.get(infoid);
		model.addAttribute("tinfo", tinfo);
		model.addAttribute("type", Integer.valueOf(request.getParameter("type")));
        setDict(model);
		return "tinfoEdit";
	}

	/**
	 * 信息管理详情
	 * 
	 * @param infoid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tinfoDetail.do")
	public String detail(long infoid, HttpServletRequest request, ModelMap model) {
		Tinfo tinfo = tinfoService.get(infoid);
		model.addAttribute("tinfo", tinfo);
		if (null != tinfo.getPic()) {
			String pic64 = Base64.encode(tinfo.getPic());
			String img = "data:image/png;base64," + pic64;
			model.addAttribute("imgSource", img);
		}
        setDict(model);
		return "tinfoView";
	}

	/**
	 * 信息管理查询（分页）
	 * 
	 * @param tinfo
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tinfoList.do")
	public String listPage(Tinfo tinfo, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		if (pageNo == null)
			pageNo = 1;
		model.addAttribute("type", request.getParameter("type"));
		Pagination pagination = tinfoService.getTinfoByPage(toMap(tinfo),
				pageNo, CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
        setDict(model);
		return "tinfoList";
	}

	/**
	 * 信息管理查询
	 * 
	 * @param tinfo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tinfoList1.do")
	public String list(Tinfo tinfo, HttpServletRequest request, ModelMap model) {
		List<Tinfo> list = tinfoService.getTinfo(toMap(tinfo));
		model.addAttribute("list", list);
		model.addAttribute("type", request.getParameter("type"));
        setDict(model);
		return "tinfoList";
	}
	
	@RequestMapping("v_tinfoListWorkGuide.do")
	public String ListWorkGuide(Tinfo tinfo, Integer pageNo, HttpServletRequest request, ModelMap model) {
		if (pageNo == null)
			pageNo = 1;
		model.addAttribute("type", request.getParameter("type"));
		Pagination pagination = tinfoService.getWorkGuideByPage(pageNo,  CookieUtils.getPageSize(request));
//		Pagination pagination = tinfoService.getTinfoByPage(toMap(tinfo), pageNo, CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
		setDict(model);
		return "workingGuideList";
	}
	


 	/***
	 * 将页面输入信息转成map
	 * 
	 * @param tinfo
	 * @return
	 */	private Map<String,Object> toMap(Tinfo tinfo){
		Map<String,Object> map=new HashMap<String, Object>();
      		if(tinfo.getInfoid()!=null&&!tinfo.getInfoid().equals("")){
			map.put("infoid", tinfo.getInfoid());
		}
		if(tinfo.getType()!=null&&!tinfo.getType().equals("")){
			map.put("type", tinfo.getType());
		}
		if(tinfo.getTitle()!=null&&!tinfo.getTitle().equals("")){
			map.put("title", tinfo.getTitle());
		}
		if(tinfo.getContent()!=null&&!tinfo.getContent().equals("")){
			map.put("content", tinfo.getContent());
		}
		if(tinfo.getAuthor()!=null&&!tinfo.getAuthor().equals("")){
			map.put("author", tinfo.getAuthor());
		}
		if(tinfo.getCreatetime()!=null&&!tinfo.getCreatetime().equals("")){
			map.put("createtime", tinfo.getCreatetime());
		}
		if(tinfo.getOwner()!=null&&!tinfo.getOwner().equals("")){
			map.put("owner", tinfo.getOwner());
		}
		if(tinfo.getAuditor()!=null&&!tinfo.getAuditor().equals("")){
			map.put("auditor", tinfo.getAuditor());
		}
		if(tinfo.getAuditstatus()!=null&&!tinfo.getAuditstatus().equals("")){
			map.put("auditstatus", tinfo.getAuditstatus());
		}      
		return map;
	}
   
	/**
	 * 设置页面所需的数据字典
	 * @param model
	 */
	private void setDict(ModelMap model){
	      model.addAttribute("wgMap", DictUtils.getDictByType(DictUtils.TWORKGUIDE_TYPE));
	}

	/**
	 * 数据校验
	 * @param model
	 */
	private WebErrors validateSave(Tinfo tinfo, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		/**if (errors.ifOutOfLength(username, "username", 1, 100)) {
			return errors;
		}  */    
		return errors;
	}

	private static Map getReqValues(HttpServletRequest request) {
		Map<String, String> vmap = new HashMap<String, String>();
		Enumeration<String> e = request.getParameterNames();
		while (e.hasMoreElements()) {
			String name = e.nextElement();
			String value1 = request.getParameter(name);
			String value = value1;
			try {
				value = new String(value1.getBytes("ISO8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			vmap.put(name, value);
		}

		return vmap;
	}
      
	@Resource
	private TinfoService tinfoService;   
}